﻿@typeparam TDialog where TDialog : ComponentBase
@typeparam TRecord where TRecord : IFormElementRecord
@using FormBuilder.Dialogs
@using FormBuilder.Models
@inject DialogService dialogService

@if(IsEditModeEnabled)
{
    <div class="draggableElement" @ondragstart:stopPropagation="true" draggable="true" @ondragstart="@(() => HandleDragStart())">
        <div class="info">
            @Record.GetType().Name
        </div>
        <div class="toolbox">
            <ul>
                <li>
                    @if (!IsViewSettingsDisabled)
                    {
                        <RadzenButton Icon="settings" ButtonStyle="ButtonStyle.Primary" Size="ButtonSize.ExtraSmall" Click="(async (e) => await HandleViewSettings())" />
                    }
                    <RadzenButton Icon="delete" ButtonStyle="ButtonStyle.Primary" Size="ButtonSize.ExtraSmall" Click="@HandleRemove" />
                </li>
            </ul>
        </div>
        @Children
        @if (IsOverlayDisplayed)
        {
            <div class="overlay">
                <RadzenIcon Icon="lock" />
            </div>
        }
    </div>
}
else 
{
    @Children
}

@code {
    [Parameter] public RenderFragment Children { get; set; }
    [Parameter] public bool IsEditModeEnabled { get; set; }
    [Parameter] public ParentEltContext ParentContext { get; set; }
    [Parameter] public WorkflowContext Context { get; set; }
    [Parameter] public TRecord Record { get; set; }
    [Parameter] public bool IsViewSettingsDisabled { get; set; } = false;

    public bool IsOverlayDisplayed
    {
        get
        {
            return Context.FormEditorContext.IsEltInvolvedInWorkflow(Record);
        }
    }

    public string ClassName
    {
        get
        {
            return $"draggableElement";
        }
    }

    private void HandleDragStart()
    {
        Context.FormEditorContext.SelectInstance(Record, ParentContext, HandleCurrentEltDropped);
    }

    private void HandleCurrentEltDropped()
    {
        ParentContext.Elements.RemoveAt(ParentContext.Index);
    }

    private void HandleRemove()
    {
        var elt = ParentContext.Elements[ParentContext.Index];
        ParentContext.Elements.Remove(elt);
    }

    private async Task HandleViewSettings()
    {
        var dic = new Dictionary<string, object>
        {
            { "Record", Record },
            { "WorkflowContext", Context }
        };
        var opts = new DialogOptions
        {
            Width = "1200px"
        };
        await dialogService.OpenAsync<TDialog>(string.Empty, dic, opts);
    }
}